// pages/oldmentality/oldmentality.js
const now = new Date();
const year = now.getFullYear()
const month = now.getMonth()
const day = now.getDate()

const db = wx.cloud.database();
const appUser = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    name: "",
    range: [],
    todayMentality: "",
    todayAssay: "",
    getTime: "",
    show: false,
    minDate: new Date(year, month < 3 ? 0 : month - 3, 1).getTime(),
    maxDate: new Date(year, month, day).getTime(),
  },
  onChange(e) {
    var index = e.detail.value
    console.log(this.data.range[index])
    this.setData({
      name: this.data.range[index].name,
      oldid: this.data.range[index].id,
    })
  },
  getName() {
    db.collection("oldmanlist").where({
      _openid: appUser.globalData.userOpenid
    }).get({
      success: res => {
        var list = res.data
        list.map(item => {
          this.data.range.push({
            name: item.name,
            id: item._id
          })
        })
        this.setData({
          range: this.data.range
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getName();
    //console.log(year + "-" + month + "-" + day)
  },
  //日历
  onDisplay() {
    this.setData({
      show: true
    });
  },
  onClose() {
    this.setData({
      show: false
    });
  },
  formatDate(date) {
    date = new Date(date);
    return `${date.getMonth() + 1}/${date.getDate()}`;
  },
  onConfirm(event) {
    this.setData({
      show: false,
      getTime: year + "/" + this.formatDate(event.detail),
    });
    console.log(this.data.getTime)

  },
  consult() {
    if (this.data.getTime == "") {
      wx.showToast({
        icon: 'error',
        title: '请选择时间'
      })
    } else if (this.data.range[0].name) {
      db.collection("oldmanlist").where({
        // mental: db.command.elemMatch({
        //   time: this.data.getTime,
        // }),
        name: this.data.range[0].name
      }).get({
        success: res => {
          let f = res.data[0].mental.find((value, index, array) => {
            return value.time === this.data.getTime;
          })
          console.log(f.ai)
          this.setData({
            todayMentality: f.up,
            todayAssay: f.ai
          })
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})